###############################################################
# Clase GET_Answer
# representa una respuesta al cliente. La respuesta a una petición
# GET. Contien un código HTTP y el contenido de HTML a enviar
###############################################################
class GET_Answer

	def initialize()
		@HTTP_code = ""
		@content = ""
		@content_type = {
			
			#text
			'html' => 'text/html',
			'txt' => 'text/plain',
			'htmls' => 'text/html',
			'xml' => 'text/xml',
			'css' => 'text/css',
			'csv' => 'text/csv',
			'htmls' => 'text/html',
			
			#image
			'ico' => 'image/vnd.microsoft.icon',
			'png' => 'image/png',
			'jpg' => 'image/jpeg',
			'jpeg' => 'image/jpeg',
			'gif' => 'image/gif',
			'svg' => 'image/svg+xml',
			'tiff' => 'image/tiff',
			
			#audio
			'wav' => 'audio/vnd.wave',
			'wma' => 'audio/x-ms-wma',
			
			#video
			'mpeg' => 'video/mpeg',
			'mp4' => 'video/mp4',
			'wmv' => 'video/x-ms-wmv',
			
			#application
			'pdf' => 'application/pdf',
			'ogg' => 'application/ogg',
			'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
			'odt' => 'application/vnd.oasis.opendocument.text',
			'odp' => 'application/vnd.oasis.opendocument.presentation',
			#---------------------------------------
			'xls' => 'application/vnd.ms-excel',
			'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
			'doc' => 'application/msword',
			'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
			'ppt' => 'application/vnd.ms-powerpoint',
			'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
			
			
		}
	end
	#------------------------------------------------------
	# retorna ya sea @HTTP_code  o @content
	#------------------------------------------------------
	attr_reader :HTTP_code, :content, :authentication
	attr_writer :HTTP_code, :content, :authentication
	
	
	#------------------------------------------------------
	# setHTTP_code asigna el código HTTP correspondiente
	# al código. Puede tener 1 o 2 parámetros y el segundo
	# lo completa con ""
	#------------------------------------------------------
	def setHTTP_code(*args)
		if args.size == 1
			setHTTP_code_1(args[0],"")
		elsif args.size == 2
			setHTTP_code_1(args[0],args[1])
		else
			setHTTP_code_1("","")
		end
	end
	
	
	def setHTTP_code_flush(code, path)
		case code
		
		when "flush ok"
			
			@content = genPage("File #{path} updated successful.","flush")
			
			@HTTP_code = "HTTP/1.1 200 OK"+"\n"
			@HTTP_code << ("Date: " + Time.now.asctime + "\n")
			@HTTP_code << "Content-Type: text/html" << "\n"
			@HTTP_code << "Content-Length: #{@content.length}"
			
		when "flush don't exist"
			
			@content = genPage("File not found, so can't flush",":S")
			
			@HTTP_code = "HTTP/1.1 404 Not Found"+"\n"
			@HTTP_code << ("Date: " + Time.now.asctime + "\n")
			@HTTP_code << "Content-Type: text/html" << "\n"
			@HTTP_code << "Content-Length: #{@content.length}"
		end
	end
	
	#------------------------------------------------------
	# setHTTP_code_down asigna el código HTTP correspondiente
	# al código (code)
	#------------------------------------------------------
	def setHTTP_code_down(code, server)
		case code
		
		when "down"
		
			@content = genPage("#{server} now in downtime.","Zzz... Zzz...")
			
			@HTTP_code = "HTTP/1.1 200 OK"+"\n"
			@HTTP_code << ("Date: " + Time.now.asctime + "\n")
			@HTTP_code << "Content-Type: text/html" << "\n"
			@HTTP_code << "Content-Length: #{@content.length}"
		
		when "can't down"
		
			@content = genPage("Can't down now. #{server} is down or asking","ups")
			
			@HTTP_code = "HTTP/1.1 200 OK"+"\n"
			@HTTP_code << ("Date: " + Time.now.asctime + "\n")
			@HTTP_code << "Content-Type: text/html" << "\n"
			@HTTP_code << "Content-Length: #{@content.length}"
			
		when "error"
		
			@content = genPage("#{server} can't down. Server #{server} not adequately answered",":S")
			
			@HTTP_code = "HTTP/1.1 200 OK"+"\n"
			@HTTP_code << ("Date: " + Time.now.asctime + "\n")
			@HTTP_code << "Content-Type: text/html" << "\n"
			@HTTP_code << "Content-Length: #{@content.length}"
			
		end
	
	end
	
	#------------------------------------------------------
	# setHTTP_code_Users asigna el código HTTP correspondiente
	# al código (code) y acción definida sobre el usuario
	# user_name
	#------------------------------------------------------
	def setHTTP_code_Users(code,action,user_name)
		case code
		
		when "user ok"
		
			@content = genUserPage("User was #{action} succesfully.","User: #{user_name}.")
		
			@HTTP_code = "HTTP/1.1 200 OK"+"\n"
			@HTTP_code << ("Date: " + Time.now.asctime + "\n")
			@HTTP_code << "Content-Type: text/html" << "\n"
			@HTTP_code << "Content-Length: #{@content.length}"
		
		when "user problem"
		
			@content = genUserPage("A problem has ocurred when asking other servers. Can't #{action} the user.","User: #{user_name}.")
		
			@HTTP_code = "HTTP/1.1 200 OK"+"\n"
			@HTTP_code << ("Date: " + Time.now.asctime + "\n")
			@HTTP_code << "Content-Type: text/html" << "\n"
			@HTTP_code << "Content-Length: #{@content.length}"
		
		
		when "user exist"
		
			@content = genUserPage("User already exist.","Can't #{action} user: #{user_name}.")
		
			@HTTP_code = "HTTP/1.1 200 OK"+"\n"
			@HTTP_code << ("Date: " + Time.now.asctime + "\n")
			@HTTP_code << "Content-Type: text/html" << "\n"
			@HTTP_code << "Content-Length: #{@content.length}"
			
		when "user don't exist"
		
			@content = genUserPage("User doesn't exist.","Can't #{action} user: #{user_name}.")
		
			@HTTP_code = "HTTP/1.1 200 OK"+"\n"
			@HTTP_code << ("Date: " + Time.now.asctime + "\n")
			@HTTP_code << "Content-Type: text/html" << "\n"
			@HTTP_code << "Content-Length: #{@content.length}"
	
		when "user progress"
		
			@content = genUserPage("Another server is processing the user","Can't #{action} user: #{user_name}.")
		
			@HTTP_code = "HTTP/1.1 200 OK"+"\n"
			@HTTP_code << ("Date: " + Time.now.asctime + "\n")
			@HTTP_code << "Content-Type: text/html" << "\n"
			@HTTP_code << "Content-Length: #{@content.length}"
		end
	end
	
	#------------------------------------------------------
	# setHTTP_code_1 asigna el código HTTP correspondiente
	# al código (code) enviado
	#------------------------------------------------------
	def setHTTP_code_1(code,ext)
		case code.downcase

			
		when "ok"
			
			@HTTP_code = "HTTP/1.1 200 OK"+"\n"
			@HTTP_code << "Server: miniServer/0.01 (Unix) (Debian/Linux)" << "\n"
			@HTTP_code << ("Date: " + Time.now.asctime + "\n")
			@HTTP_code << "Content-type: #{getContentType(ext)}" + "\n"
			@HTTP_code << "Content-Length: #{@content.length}" 

		
		when "link not found"
			
			@content = errorPage("404 Link Not Found.")

			@HTTP_code = "HTTP/1.1 404 Not Found"+"\n"
			@HTTP_code << "Server: miniServer/0.01 (Unix) (Debian/Linux)" << "\n"
			@HTTP_code << ("Date: " + Time.now.asctime + "\n")
			@HTTP_code << "Content-type: text/html" << "\n"
			@HTTP_code << "Content-Length: #{@content.length}"
		
		
		when "not found"
			
			@content = genPage("404 Not Found.","Error")

			@HTTP_code = "HTTP/1.1 404 Not Found"+"\n"
			@HTTP_code << "Server: miniServer/0.01 (Unix) (Debian/Linux)" << "\n"
			@HTTP_code << ("Date: " + Time.now.asctime + "\n")
			@HTTP_code << "Content-type: text/html" << "\n"
			@HTTP_code << "Content-Length: #{@content.length}"
			

		when "folder found"
			
			@HTTP_code = "HTTP/1.1 200 OK"+"\n"
			@HTTP_code << "Server: miniServer/0.01 (Unix) (Debian/Linux)" << "\n"
			@HTTP_code << ("Date: " + Time.now.asctime + "\n")
			@HTTP_code << "Content-Type: text/html" << "\n"
			@HTTP_code << "Content-Length: #{@content.length}"
			
			 

		when "authorization required"
			
			
			@content = genPage("401 Unauthorized.","Error")
			
			@HTTP_code = "HTTP/1.1 401 Authorization Required"+"\n"
			@HTTP_code << "Server: HTTPd/1.0" << "\n"
			@HTTP_code << "Date: " + Time.now.asctime + "\n"
			@HTTP_code << "WWW-Authenticate: Basic realm=\"Secure Area\"" << "\n"
			@HTTP_code << "Content-Type: text/html" << "\n"
			@HTTP_code << "Content-Length: #{@content.length}"
			
			
		
		when "downtime"
			
			@content = genPage("503 Now in downtime. Service Unavailable.","Zzz... Zzz...")
			
			@HTTP_code = "HTTP/1.1 503 Service Unavailable"+"\n"
			@HTTP_code << ("Date: " + Time.now.asctime + "\n")
			@HTTP_code << "Content-Type: text/html" << "\n"
			@HTTP_code << "Content-Length: #{@content.length}"
		
			
		when "bad request"
			
			@content = genPage("400 Bad Request.","Error")
			
			@HTTP_code = "HTTP/1.1 400 Bad Request"+"\n"
			@HTTP_code << ("Date: " + Time.now.asctime + "\n")
			@HTTP_code << "Content-Type: text/html" << "\n"
			@HTTP_code << "Content-Length: #{@content.length}"
			
		else
			
			@content = genPage("400 #{code}.","Error")
			
			@HTTP_code = "HTTP/1.1 400 Bad Request"+"\n"
			@HTTP_code << ("Date: " + Time.now.asctime + "\n")
			@HTTP_code << "Content-Type: text/html" << "\n"
			@HTTP_code << "Content-Length: #{@content.length}"
			
		end
	end
	
	
	#------------------------------------------------------
	# retorna una página html con una plantilla de error
	#------------------------------------------------------
	def genUserPage(msj,msj2)
		title = "User management"
		temp = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\""+"\n"
		temp << " \"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\">"+"\n"
		temp << "<HTML>"+"\n"
		temp << "  <HEAD>"+"\n"
		temp << "    <TITLE>#{title}</TITLE>"+"\n"
		temp << "    <META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=ISO-8859-1\">"+"\n"
		temp << "  </HEAD>"+"\n"
		temp << "  <BODY>"+"\n"
		temp << "  <H1>#{msj}</H1>"+"\n"
		temp << "  <H2>#{msj2}</H2>"+"\n"
		temp << "  </BODY>"+"\n"
		temp << "</HTML>"+"\n"
		return temp
	end
	
	#------------------------------------------------------
	# retorna una página html con una plantilla de error
	#------------------------------------------------------
	def genPage(msj,title)
		temp = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\""+"\n"
		temp << " \"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\">"+"\n"
		temp << "<HTML>"+"\n"
		temp << "  <HEAD>"+"\n"
		temp << "    <TITLE>#{title}</TITLE>"+"\n"
		temp << "    <META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=ISO-8859-1\">"+"\n"
		temp << "  </HEAD>"+"\n"
		temp << "  <BODY><H1>#{msj}</H1></BODY>"+"\n"
		temp << "</HTML>"+"\n"
		return temp
	end
	
	#------------------------------------------------------
	# retorna una página html con una plantilla de una carpeta
	#------------------------------------------------------
	def setfolderPage( root , part_path , complete_path , port)

		temp_part_path = part_path
		
		temp = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 3.2 Final//EN\">" + "\n"
		temp << "<html>" + "\n"
		temp << "<head>" + "\n"
		temp << "<title>Index of /#{temp_part_path.gsub("á", "&aacute;").gsub("é", "&eacute;").gsub("í", "&iacute;").gsub("ó", "&oacute;").gsub("ú", "&uacute;")}</title>" + "\n"
		temp << "</head>" + "\n"
		temp << "<body>" + "\n"
		temp << "<h1>Index of /#{temp_part_path.gsub("á", "&aacute;").gsub("é", "&eacute;").gsub("í", "&iacute;").gsub("ó", "&oacute;").gsub("ú", "&uacute;")}</h1>" + "\n"
		temp << "" + "\n"
		temp << "<pre>" + "\n"
		#.gsub("á", "&aacute;").gsub("é", "&eacute;").gsub("í", "&iacute;").gsub("ó", "&oacute;").gsub("ú", "&uacute;")
		espacios = 27
		espacios2 = 27
		temp << "   Name#{" "*(espacios-"Name".length)}Last modified#{" "*(espacios2-"Last modified".length)}Size" + "\n"
		temp << "<hr>   <a href=\"../\">Parent Directory</a>#{" "*(espacios-"Parent Directory".length+espacios2)}--" + "\n"
		temp << "" + "\n"
		
		 
		
		#puts "--------------------------------------------------------------------------------"
		carpeta = Dir.new(complete_path).entries
		
		array = Array.new
		
		
		for a in carpeta
			
			archivo = File.new(complete_path+a)
			ctime = File.new(complete_path+a).ctime.asctime
				
			if(File.directory?(complete_path+a))
				
				if(a=="."||a=="..")
					#puts "no poner el ."
				else


					inicio = "#{a}/"
					cant = espacios-inicio.length

					link = inicio.gsub("á", "&aacute;").gsub("é", "&eacute;").gsub("í", "&iacute;").gsub("ó", "&oacute;").gsub("ú", "&uacute;")
					cant += ((link.length-inicio.length)/6).to_i
					#print ".#{inicio}. .#{link}. - #{inicio.length} - #{link.length} - #{cant}\n"

					size = "--"
					temp << ("   <a href=\"#{link}\">#{link}</a>#{" "*cant}#{ctime}#{" "*(espacios2-ctime.to_s.length)}#{size}" + "\n")
					
				end
				
				
			elsif(File.file?(complete_path+a))
			
				inicio = "#{a}"
				cant = espacios-inicio.length

				link = inicio.gsub("á", "&aacute;").gsub("é", "&eacute;").gsub("í", "&iacute;").gsub("ó", "&oacute;").gsub("ú", "&uacute;")
				cant += ((link.length-inicio.length)/6).to_i
				#print ".#{inicio}. .#{link}. - #{inicio.length} - #{link.length} - #{cant}\n"
				size = (archivo.read().length).to_s
				array << ("   <a href=\"#{link}\">#{link}</a>#{" "*cant}#{ctime}#{" "*(espacios2-ctime.to_s.length)}#{size} bytes" + "\n")
				
			end
			
		end
		#puts "--------------------------------------------------------------------------------"
		#hasta ahorita ya se pusieron las carpetas.. faltan los archivos (almacenados en array)
		array.each{ |i|
			temp << i
		}
		#puts "--------------------------------------------------------------------------------"
		
		temp << "" + "\n"
		temp << "<hr>" + "\n"
		temp << "</pre>" + "\n"
		temp << "" + "\n"
		temp << "<address>miniServerRuby/1.0.27 (Unix) (Debian/Linux) Port #{port} - Mart&iacute;n Guzm&aacute;n - 08041</address>" + "\n"
		temp << "" + "\n"
		temp << "</body></html>"
		
		@content = temp
		
	end
	
	#------------------------------------------------------
	# retorna el tipo del retorno
	#-----------------------------------------------------
	def getContentType(ext)
		if(@content_type.has_key?(ext.downcase))
		
			return @content_type[ext.downcase]
			
		end
		
		
		return "text/plain"
	end
	
	#------------------------------------------------------
	# retorna la respuesta completa
	#------------------------------------------------------
	def answer()
		var = "#{@HTTP_code}" + "\n"
		var << "\n"
		var << @content
		return var
	end
end
